<template>
  <div class="hello">
    <div id="map" class="map" tabindex="0"></div>
  </div>
  
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import { Point} from "ol/geom";
import { fromLonLat } from "ol/proj";
import { Fill, Circle, Style } from "ol/style";
export default {
  name: "HelloWorld",
  data() {
    return {
      map: null,
    };
  },

  methods: {
    // 显示点
    drawTyphoonPath: async function () {
      const data = {
    "数据": "测试",
    "points": [
      {
        "time": "2021-06-23 08:00:00",
        "lng": "118.150",
        "lat": "34.030",
        "id": "555"
      
      },
      {
        "time": "2021-06-26 02:00:00",
        "lng": "120.210",
        "lat": "31.850",
        "id": "655"
      }]
  }
      console.log(data);
      let points = data.points;
      let features = [];

      let positions = [];
      for (let i = 0; i < points.length; i++) {
        let position = [points[i].lng, points[i].lat];
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position)),
        });
        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: 'red',
              }),
              radius: 10,
            }),
          })
        );
        featurePoint.set('pointData',data.points[i])
        features.push(featurePoint);
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource();
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },

    // 注册一个click事件
    designClickOnMap: function () {
      let _this = this;
      this.map.on("click", function (ev) {
        let pixel = ev.pixel;
        let feature = _this.map.forEachFeatureAtPixel(
          pixel,
          function (feature) {
            return feature;
          }
        );
        if (feature) {
          console.log(`output->feature.get('typhoonPoint')`,feature.get('pointData'))
        console.log(`output->`,feature)
        } else {
          console.log("no feature");
        }
      });
    },
  },
  mounted() {
    this.map = new Map({
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      target: "map",
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });
    this.drawTyphoonPath();
    this.designClickOnMap()
  },
};
</script>

<style scoped>
.map {
  width: 100%;
  height: 100vh;
}
</style>
